package com.online.service.user;

import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.online.dao.user.UserDao;
import com.online.model.user.BlogInfo;
import com.online.model.user.RoleInfo;
import com.online.model.user.UserInfo;
import com.online.service.ServiceException;
import com.online.util.Digests;
import com.online.util.Encodes;

@Service
public class UserService {

	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	private static final int SALT_SIZE = 8;

	@Autowired
	private UserDao userDao;

	public List<UserInfo> search(Map<String, Object> params) {
		params.put("total", userDao.searchTotal(params));
		List<UserInfo> users = userDao.search(params);
		for (UserInfo user : users) {
			if (!user.getBlogs().isEmpty()) {
				for (BlogInfo blog : user.getBlogs()) {
					System.out.println(blog.getContent());
				}
			}
		}
		return userDao.search(params);
	}

	public UserInfo getById(Integer id) {
		return userDao.getById(id);
	}

	public UserInfo getByLoginName(String loginName) {
		return userDao.getByLoginName(loginName);
	}

	/** 查询指定用户角色 */
	public List<RoleInfo> getRoleByUserLoginName(String loginName) {
		return userDao.getRoleByUserLoginName(loginName);
	}

	@Transactional(readOnly = false)
	public void add(UserInfo user) {
		if (userDao.getByLoginName(user.getLoginName()) != null) {
			throw new ServiceException("登录名已存在");
		}
		entryptPassword(user);
		userDao.add(user);
		userDao.addUserRole(user.getId(), 1);
	}

	@Transactional(readOnly = false)
	public void update(UserInfo user) {
		userDao.update(user);
	}

	@Transactional(readOnly = false)
	public void delete(Integer id) throws ServiceException {
		// 验证角色
		Subject subject = SecurityUtils.getSubject();
		if (subject.hasRole("admin")) {
			userDao.delete(id);
		} else {
			throw new ServiceException("你没有权限删除用户");
		}
	}

	@Transactional(readOnly = false)
	public void delete2(Integer id) throws ServiceException {
		// 验证权限
		Subject subject = SecurityUtils.getSubject();
		if (subject.isPermitted("user:delete")) {
			userDao.delete(id);
		} else {
			throw new ServiceException("你没有权限删除用户");
		}
	}

	/** 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash */
	private void entryptPassword(UserInfo user) {
		byte[] salt = Digests.generateSalt(SALT_SIZE);
		user.setSalt(Encodes.encodeHex(salt));

		byte[] hashPassword = Digests.sha1(user.getPassword().getBytes(), salt,
				HASH_INTERATIONS);
		user.setPassword(Encodes.encodeHex(hashPassword));
	}
}
